/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.jy.springbootcmsservice.common.base.service.impl;

import com.jy.springbootcmsservice.common.base.dao.TreeDao;
import com.jy.springbootcmsservice.common.base.entity.TreeEntity;
import com.jy.springbootcmsservice.common.base.service.TreeService;
import com.jy.springbootcmsservice.common.utils.Reflections;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service基类
 * @author ThinkGem
 * @version 2014-05-16
 */
@Transactional(readOnly = true)
public class TreeServiceImpl<D extends TreeDao<T>, T extends TreeEntity<T>> extends CrudServiceImpl<D, T> implements TreeService<T> {
	
	@Transactional(readOnly = false)
	@Override
	public int save(T entity) {

		int result;

		@SuppressWarnings("unchecked")
		Class<T> entityClass = Reflections.getClassGenricType(getClass(), 1);
		
		// 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
		if (entity.getParentId() == null){
			if(entity.getParent() == null){
				try {
					entity.setParent(entityClass.newInstance());
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
			entity.getParent().setId("0");
		}

		// 获取修改前的parentIds，用于更新子节点的parentIds
		String oldParentIds = entity.getParentIds();

		// 设置新的父节点串
		entity.setParentIds((oldParentIds == null ? "" : oldParentIds) + entity.getParentId()+",");

		// 如果没有写入顺序，则默认为于其平级的排序+30
		if(entity.getSort() == null){
			entity.setSort(30);
		}

		// 保存或更新实体
		result = super.save(entity);

		// 更新子节点 parentIds
		T o = null;
		try {
			o = entityClass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		o.setParentIds("%,"+entity.getId()+",%");
		List<T> list = dao.findByParentIdsLike(o);
		for (T e : list){
			if (e.getParentIds() != null && oldParentIds != null){
				e.setParentIds(e.getParentIds().replace(oldParentIds, entity.getParentIds()));
				preUpdateChild(entity, e);
				dao.updateParentIds(e);
			}
		}

		return result;
	}
	
	/**
	 * 预留接口，用户更新子节前调用
	 * @param childEntity
	 */
	protected void preUpdateChild(T entity, T childEntity) {
		
	}
}
